﻿using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Tippelde.Services.Accounts;
using Tippelde.Web.Helpers;

namespace Tippelde.Web.Controllers
{
    [Authorize]
    public class UserController : Controller
    {
        [Dependency]
        public UserManager UserManager { get; set; }


        [Authorize(Roles = "admin")]
        public async Task<ActionResult> Index(int? page)
        {
            var model = await UserManager.GetUsersWithRoles(page);
            return View(model);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "admin")]
        public async Task<ActionResult> ChangeRole(string userId, string roleName, bool isSet, int? currentPage)
        {
            if (isSet)
            {
                if(! await UserManager.IsInRoleAsync(userId, roleName))
                    await UserManager.AddToRoleAsync(userId, roleName);
            }
            else
            {
                if (await UserManager.IsInRoleAsync(userId, roleName))
                    await UserManager.RemoveFromRoleAsync(userId, roleName);
            }
            return RedirectToAction("Index", new { page = currentPage });
        }

        [Authorize(Roles="admin")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Delete(string userId)
        {
            await UserManager.DeleteUser(userId, User.Identity.Name);
            CacheManager.Current.InvalidateUserGroups();
            return RedirectToAction("Index");
        }
    }
}